package com.mall.shopping.services;

import com.alibaba.fastjson.JSONObject;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.CartItemConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import com.mall.user.constants.SysRetCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ICartServiceImpl implements ICartService {


    @Autowired
    RedissonClient redissonClient;
    @Autowired
    ItemMapper itemMapper;
    @Override

    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse response = new CartListByIdResponse();
        try {
//            参数校验
            request.requestCheck();
            RMap<String, String> map = redissonClient.getMap(request.getUserId().toString());
            List<CartProductDto> list = new ArrayList<>();
            for (String key : map.keySet()) {
                String value = map.get(key);
                CartProductDto cartProductDto = JSONObject.parseObject(value, CartProductDto.class);
                list.add(cartProductDto);
            }
            response.setCartProductDtos(list);

            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }catch (Exception e){
            return response;
//            log.error("ICartServiceImpl getCartListById occur Exception :"+e);
//            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse response = new AddCartResponse();
        Long itemId = request.getItemId();
        Integer num = request.getNum();
        try {
            request.requestCheck();
            RMap<String, String> map = redissonClient.getMap(request.getUserId().toString());
            if (map.containsKey(itemId.toString())){//购物车中存在
                String oldJsonString = map.get(itemId.toString());
                CartProductDto cartProductDto = JSONObject.parseObject(oldJsonString, CartProductDto.class);
                map.remove(itemId);
                Long limitNum = cartProductDto.getLimitNum();
                Long oldNum = cartProductDto.getProductNum();
                if (oldNum + num > limitNum)throw new Exception("选购商品数量大于限制");
                cartProductDto.setProductNum(oldNum + num);
                String newString = JSONObject.toJSONString(cartProductDto);
                map.put(itemId.toString(),newString);
            }else {
                //购物车中不存在
                Item item = itemMapper.selectByPrimaryKey(itemId);
                CartProductDto cartProductDto = CartItemConverter.item2Dto(item);
                cartProductDto.setProductNum(num.longValue());
                cartProductDto.setChecked("true");
                String newString = JSONObject.toJSONString(cartProductDto);
                map.put(itemId.toString(),newString);
            }

        }catch (Exception e){
            log.error("ICartServiceImpl addToCart occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        try {
            request.requestCheck();
            RMap<String, String> map = redissonClient.getMap(request.getUserId().toString());
            String oldJsonString = map.get(request.getProductId().toString());
            CartProductDto cartProductDto = JSONObject.parseObject(oldJsonString, CartProductDto.class);
            cartProductDto.setProductNum(request.getProductNum().longValue());
            if (!"1".equals(request.getChecked()))
            cartProductDto.setChecked(request.getChecked());
            String newString = JSONObject.toJSONString(cartProductDto);
            map.put(request.getProductId().toString(),newString);
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }catch (Exception e){
//            log.error("ICartServiceImpl updateCartNum occur Exception :"+e);
//            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            return response;
        }
        return response;
    }
    //ToDo 已写完 待校验
    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse response = new CheckAllItemResponse();
//        try {
            //检验参数的有效性
            request.requestCheck();
            RMap<String, String> map = redissonClient.getMap(request.getUserId().toString());
            for (String key : map.keySet()) {
                String value = map.get(key);
                System.out.println(value);
                CartProductDto cartProductDto = JSONObject.parseObject(value, CartProductDto.class);
                if (!cartProductDto.getChecked().equals(request.getChecked()))
                cartProductDto.setChecked(request.getChecked());
                String newString = JSONObject.toJSONString(cartProductDto);
                System.out.println(newString);
                String put = map.put(key, newString);
            }
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
//        }catch (Exception e){
////            log.error("ICartServiceImpl checkAllCartItem occur Exception :"+e);
////            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            return response;
        }

//        return response;
//    }



    //ToDo  已写完  待校验
    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse response = new DeleteCartItemResponse();
        try {
            //检验参数的有效性
            request.requestCheck();
            RMap<String, String> map = redissonClient.getMap(request.getUserId().toString());
            String remove = map.remove(request.getItemId().toString());
            //数据库中数据校验
            CartProductDto cartProductDto = JSONObject.parseObject(remove, CartProductDto.class);
            if (cartProductDto==null)throw new Exception("删除购物车异常");
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }catch (Exception e){
//            log.error("ICartServiceImpl deleteCartItem occur Exception :"+e);
//            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            return response;
        }

        return response;
    }
    //ToDo  已写完  待校验
    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {

        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();
        try {
            request.requestCheck();
            RMap<String, String> map = redissonClient.getMap(request.getUserId().toString());
            for (String key : map.keySet()) {
                String value = map.get(key);
                CartProductDto cartProductDto = JSONObject.parseObject(value, CartProductDto.class);
                if ("true".equals(cartProductDto.getChecked()))map.remove(key);
            }
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }catch (Exception e){
//            log.error("ICartServiceImpl deleteCheckedItem occur Exception :"+e);
//            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            return response;
        }
        return response;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        return null;
    }
}
